import { SqlBuildResult, SqlExecuteResult, SqlExecutor } from './types';

/**
 * 可执行接口
 * 为SQL构建器提供执行能力
 */
export interface Executable<T, R = any> {
  /**
   * 执行SQL并返回结果
   * @param executor SQL执行器
   */
  execute(executor: SqlExecutor): R;
}

/**
 * 可执行查询接口
 * 为查询构建器提供执行能力
 */
export interface ExecutableQuery<T> extends Executable<T, T[]> {
  /**
   * 执行查询并返回结果列表
   * @param executor SQL执行器
   */
  execute(executor: SqlExecutor): T[];
  
  /**
   * 执行查询并返回单个结果
   * @param executor SQL执行器
   */
  executeOne(executor: SqlExecutor): T | undefined;
  
  /**
   * 执行查询并返回总数
   * @param executor SQL执行器
   */
  executeCount(executor: SqlExecutor): number;
}

/**
 * 可执行插入接口
 * 为插入构建器提供执行能力
 */
export interface ExecutableInsert<T> extends Executable<T, SqlExecuteResult> {
  /**
   * 执行插入并返回执行结果
   * @param executor SQL执行器
   */
  execute(executor: SqlExecutor): SqlExecuteResult;
  
  /**
   * 执行插入并返回最后插入的ID
   * @param executor SQL执行器
   */
  executeGetId(executor: SqlExecutor): number | bigint;
}

/**
 * 可执行更新接口
 * 为更新构建器提供执行能力
 */
export interface ExecutableUpdate<T> extends Executable<T, SqlExecuteResult> {
  /**
   * 执行更新并返回执行结果
   * @param executor SQL执行器
   */
  execute(executor: SqlExecutor): SqlExecuteResult;
  
  /**
   * 执行更新并返回受影响的行数
   * @param executor SQL执行器
   */
  executeGetChanges(executor: SqlExecutor): number;
}

/**
 * 可执行删除接口
 * 为删除构建器提供执行能力
 */
export interface ExecutableDelete<T> extends Executable<T, SqlExecuteResult> {
  /**
   * 执行删除并返回执行结果
   * @param executor SQL执行器
   */
  execute(executor: SqlExecutor): SqlExecuteResult;
  
  /**
   * 执行删除并返回受影响的行数
   * @param executor SQL执行器
   */
  executeGetChanges(executor: SqlExecutor): number;
}

/**
 * 执行Mixin
 * 为SQL构建器提供执行能力的Mixin
 */
export function withExecutable<T, B extends { build(): SqlBuildResult }>(Base: new (...args: any[]) => B) {
  return class extends Base implements Executable<T> {
    public execute(executor: SqlExecutor): SqlExecuteResult {
      const result = this.build();
      return executor.execute(result.sql, result.params);
    }
  };
}

/**
 * 查询执行Mixin
 * 为查询构建器提供执行能力的Mixin
 */
export function withExecutableQuery<T, B extends { build(): SqlBuildResult; mapToEntity(rows: any[]): T[]; mapToSingleEntity(row: any): T | undefined }>(
  Base: new (...args: any[]) => B
) {
  return class extends Base implements ExecutableQuery<T> {
    public execute(executor: SqlExecutor): T[] {
      const result = this.build();
      const rows = executor.query(result.sql, result.params);
      return this.mapToEntity(rows);
    }
    
    public executeOne(executor: SqlExecutor): T | undefined {
      const result = this.build();
      const row = executor.queryOne(result.sql, result.params);
      return this.mapToSingleEntity(row);
    }
    
    public executeCount(executor: SqlExecutor): number {
      const result = this.build();
      const row = executor.queryOne<{ total: number }>(result.sql, result.params);
      return row?.total || 0;
    }
  };
} 